import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: user
 * Date: 2024-04-20
 * Time: 16:07
 */
public class MyHeap {
    public int[] elem;
    public int usedSize;
    public MyHeap(){
        this.elem = new int[10];
    }
    public void init(int[] array){
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length * 2);
        }
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    private boolean isFull(){
        return usedSize == elem.length;
    }
    public void createHeap(){
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }
    public void shiftDown(int parent,int end){
        int child = 2 * parent + 1;
        while(child < end){
            if(child + 1 < end&&elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[parent] < elem[child]){
                swap(parent,child);
               parent =  child;
                child =  2 * parent + 1;
            }
            else{
                break;
            }
        }
    }
    private void swap(int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length * 2);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize - 1);
    }
    public void shiftUp(int child){
        int parent =( child - 1) / 2;
        while (parent >= 0){
            if (elem[parent] < elem[child]){
                swap(parent,child);
                child = parent;
                parent =( child - 1) / 2;
            }
            else{
                break;
            }
        }
    }
    public int poll(){
        if(isempty()){
            return -1;
        }
        int ret = elem[0];
        swap(0,usedSize - 1);
        usedSize--;
        shiftDown(0,usedSize);
        return ret;
    }
    private boolean isempty(){
        return usedSize == 0;
    }
    public void heapSort(){
        int endIndex = usedSize - 1;
        while(endIndex >= 0){
            swap(0,endIndex);
            shiftDown(0,endIndex);
            endIndex--;
        }
    }
}
